package com.jjlin.chapter_2;

import java.util.*;
public class CD158{
    public static class Node{
        public int val;
        public Node next;
        public Node(int data){
            this.val = data;
        }
    }

    //创建环形单链表
    public static Node createNodeList(int[] nums){
        Node head = new Node(nums[0]);
        Node pre = head;
        Node cur = null;
        for(int i = 1; i < nums.length; i++){
            cur = new Node(nums[i]);
            pre.next = cur;
            pre = cur;
        }
        pre.next = head;
        return head;
    }

    //打印环形单链表
    public static void printNodeList(Node head){
        if(head != null){
            System.out.print(head.val + " ");
            Node cur = head.next;
            while(cur != head){
                System.out.print(cur.val + " ");
                cur = cur.next;
            }
        }
    }

    //向有序的环形单链表中插入新节点
    public static Node insertNum(Node head, int num){
        Node node = new Node(num);
        if(head == null){
            node.next = node;
            return node;
        }
        Node pre = head;
        Node cur = head.next;
        while(cur != head){
            if(pre.val <= num && cur.val >= num){
                break;
            }
            pre = cur;
            cur = cur.next;
        }
        pre.next = node;
        node.next = cur;
        return head.val <= num ? head : node;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0; i < n; i++){
            nums[i] = sc.nextInt();
        }
        int num = sc.nextInt();
        Node head = createNodeList(nums);
        head = insertNum(head, num);
        printNodeList(head);
    }
}

